package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	Name   string `label:"Name is: "`
	Age    int    `label:"Age is: "`
	Gender string `label:"Gender is: " default:"unknown"`
}

func main() {
	person := Person{Name: "MING", Age: 29}
	err := Print(person)
	if err != nil {
		panic(err)
	}
}

// Print 根据tag输出内容
func Print(obj interface{}) error {
	// 取 Value
	v := reflect.ValueOf(obj)
	for i := 0; i < v.NumField(); i++ {
		// 获取Tag
		field := v.Type().Field(i)
		tag := field.Tag

		// 解析label和default
		label := tag.Get("label")
		defaultValue := tag.Get("default")

		value := fmt.Sprintf("%v", v.Field(i))
		if value == "" {
			// 如果没有指定值，则用默认值代替
			value = defaultValue
		}
		fmt.Println(label + value)
	}
	return nil
}
